// 实习申请控制器
package org.example.backend.controller;

import jakarta.validation.Valid;
import org.example.backend.dto.InternshipApplicationDetailDto;
import org.example.backend.dto.InternshipApplicationDto;
import org.example.backend.dto.PageResponseDto;
import org.example.backend.entity.Company;
import org.example.backend.entity.InternshipApplication;
import org.example.backend.entity.Student;
import org.example.backend.entity.User;
import org.example.backend.exception.BusinessException;
import org.example.backend.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/internship-applications")
@CrossOrigin
public class InternshipApplicationController {

    private static final Logger logger = LoggerFactory.getLogger(InternshipApplicationController.class);

    private final InternshipApplicationService internshipApplicationService;
    private final InternshipPositionService internshipPositionService;
    private final StudentService studentService;
    private final CompanyService companyService;
    private final UserService userService;

    public InternshipApplicationController(InternshipApplicationService internshipApplicationService,
                                           InternshipPositionService internshipPositionService,
                                           StudentService studentService,
                                           CompanyService companyService,
                                           UserService userService) {
        this.internshipApplicationService = internshipApplicationService;
        this.internshipPositionService = internshipPositionService;
        this.studentService = studentService;
        this.companyService = companyService;
        this.userService = userService;
    }

    /**
     * 学生提交实习申请
     */
    @PostMapping
    @PreAuthorize("hasRole('STUDENT')")
    public ResponseEntity<?> submitApplication(@Valid @RequestBody InternshipApplicationDto applicationDto) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 获取学生信息
            Student student = studentService.getStudentByUserId(user.getId());

            // 提交申请
            InternshipApplication application = internshipApplicationService.submitApplication(applicationDto, student.getId());

            Map<String, Object> response = new HashMap<>();
            response.put("message", "实习申请提交成功");
            response.put("application", application);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("提交实习申请失败", e);
            return ResponseEntity.badRequest().body("提交失败：" + e.getMessage());
        }
    }

    /**
     * 学生获取自己的申请列表（包含关联信息）
     */
    @GetMapping("/my")
    @PreAuthorize("hasRole('STUDENT')")
    public ResponseEntity<PageResponseDto<InternshipApplicationDetailDto>> getMyApplicationsWithDetails(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 获取学生信息
            Student student = studentService.getStudentByUserId(user.getId());

            Page<InternshipApplicationDetailDto> applicationPage = internshipApplicationService.getApplicationsWithDetailsByStudent(
                    student.getId(), page, size);

            PageResponseDto<InternshipApplicationDetailDto> response = new PageResponseDto<>(
                    applicationPage.getContent(),
                    applicationPage.getTotalElements(),
                    applicationPage.getTotalPages(),
                    page,
                    size
            );

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取申请列表失败", e);
            return ResponseEntity.badRequest().body(null);
        }
    }

    /**
     * 获取申请详情（包含关联信息）
     */
    @GetMapping("/{applicationId}")
    public ResponseEntity<?> getApplicationWithDetails(@PathVariable Long applicationId) {
        try {
            InternshipApplicationDetailDto applicationDto = internshipApplicationService.getApplicationWithDetails(applicationId);
            return ResponseEntity.ok(applicationDto);
        } catch (Exception e) {
            logger.error("获取申请详情失败", e);
            return ResponseEntity.badRequest().body("获取信息失败：" + e.getMessage());
        }
    }

    /**
     * 学生取消申请
     */
    @PutMapping("/{applicationId}/cancel")
    @PreAuthorize("hasRole('STUDENT')")
    public ResponseEntity<?> cancelApplication(@PathVariable Long applicationId) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 获取学生信息
            Student student = studentService.getStudentByUserId(user.getId());

            // 取消申请
            InternshipApplication application = internshipApplicationService.cancelApplication(applicationId, student.getId());

            Map<String, Object> response = new HashMap<>();
            response.put("message", "申请已取消");
            response.put("application", application);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("取消申请失败", e);
            return ResponseEntity.badRequest().body("取消失败：" + e.getMessage());
        }
    }

    /**
     * 企业获取收到的申请列表（包含关联信息）
     */
    @GetMapping("/company")
    @PreAuthorize("hasRole('COMPANY')")
    public ResponseEntity<PageResponseDto<InternshipApplicationDetailDto>> getCompanyApplicationsWithDetails(
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 获取企业信息
            Company company = companyService.getCompanyByUserId(user.getId());

            Page<InternshipApplicationDetailDto> applicationPage = internshipApplicationService.getApplicationsWithDetailsByCompany(
                    company.getId(), status, page, size);

            PageResponseDto<InternshipApplicationDetailDto> response = new PageResponseDto<>(
                    applicationPage.getContent(),
                    applicationPage.getTotalElements(),
                    applicationPage.getTotalPages(),
                    page,
                    size
            );

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取申请列表失败", e);
            return ResponseEntity.badRequest().body(null);
        }
    }


    /**
     * 企业处理申请（通过或拒绝）
     */
    @PutMapping("/{applicationId}/process")
    @PreAuthorize("hasRole('COMPANY')")
    public ResponseEntity<?> processApplication(@PathVariable Long applicationId,
                                               @RequestParam Integer status,
                                               @RequestParam(required = false) String rejectReason) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 获取企业信息
            Company company = companyService.getCompanyByUserId(user.getId());

            // 处理申请
            InternshipApplication application = internshipApplicationService.processApplication(applicationId, company.getId(), status, rejectReason);

            String message = status == 1 ? "申请已通过" : "申请已拒绝";
            Map<String, Object> response = new HashMap<>();
            response.put("message", message);
            response.put("application", application);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("处理申请失败", e);
            return ResponseEntity.badRequest().body("处理失败：" + e.getMessage());
        }
    }

    /**
     * 管理员获取所有申请列表（包含关联信息）
     */
    @GetMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<PageResponseDto<InternshipApplicationDetailDto>> getAllApplicationsWithDetails(
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Page<InternshipApplicationDetailDto> applicationPage = internshipApplicationService.getAllApplicationsWithDetails(status, page, size);

            PageResponseDto<InternshipApplicationDetailDto> response = new PageResponseDto<>(
                    applicationPage.getContent(),
                    applicationPage.getTotalElements(),
                    applicationPage.getTotalPages(),
                    page,
                    size
            );

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取申请列表失败", e);
            return ResponseEntity.badRequest().body(null);
        }
    }
}
